<template>
  <div class="list-item">
    <h3 class="title">
      <van-icon name="shop-o" />
      <span class="title__name">商城自营</span>
    </h3>
    <div v-for="(item, idx) in goodsList" :key="idx" class="item">
      <image-pic width="80" height="80" fit="fill" :src="item.picUrl || item.goodsImg" />
      <div class="item__main">
        <p class="item__main__desc van-multi-ellipsis--l2">
          {{ item.goodsName }}
        </p>
        <p class="item__main__attr">
          <span
            v-for="(specification, index) in item.specifications"
            :key="index"
          >{{ specification }}</span>
        </p>
      </div>
      <div class="item__price">
        <span class="item__price__price" v-if="item.priceType == 1">¥{{ item.price || item.goodsPrice }}</span>
        <span class="item__price__price" v-if="item.priceType == 2">{{ item.price || item.goodsPrice }}积分</span>

        <span class="item__price__count">x{{ item.number || item.goodsCount }}</span>
      </div>
    </div>
    <van-cell-group>
      <van-cell title="商品金额" v-if="priceType === 3 || priceType === 1 || priceType == undefined">
        <span  class="red">{{ type == 2?0: goodsAmount }} 元</span>
        <!-- <span v-if="goodsList[0].priceType == 2" class="red">{{ type == 2?0: goodsAmount }} 积分</span> -->
      </van-cell>
      <!-- <van-cell title="余额抵扣">
        <span  class="red">{{ type == 2?0: goodsAmount }} 元</span>
      </van-cell> -->
      <van-cell title="所需积分" v-if="priceType === 3 || priceType === 2">
        <span v-if="priceType == 2" class="red">{{ type == 2?0: goodsAmount }} </span>
        <span v-if="priceType == 3" class="red">{{ type == 2?0: pointAmount }} </span>
      </van-cell>
      <van-cell title="运费">
        <span class="red">{{ type == 2?0: freightPrice }} 元</span>
      </van-cell>
      <van-cell title="优惠券">
        <span class="red">不可用</span>
      </van-cell>
      <van-field v-model="message" placeholder="请输入备注" label="订单备注">
        <template slot="icon">{{ 500 }}/50</template>
      </van-field>
    </van-cell-group>

    <van-submit-bar
      :price="orderTotalAmount * 100"
      label="合计："
      button-text="提交订单"
      :disabled="false"
      @submit="onSubmit"
    >
      <template slot="price">
        <span v-if="priceType == 1 || priceType == 3" class="red">￥{{ orderTotalAmount * 100 }} 元</span>
        <span v-if="priceType == 2 " class="red">{{ orderTotalAmount * 100 }} 积分</span>
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import { getCheckedGoods, getGoodsPro } from '@/api/cart'
import { goodsPointDeduction,getInfo } from '@/api/user'
import { mapGetters } from 'vuex'
import { submit, searchResult, updateOrderState } from '@/api/order'
export default {
  data() {
    return {
      message: '',
      goodsAmount: 0,
      pointAmount:0,
      orderTotalAmount: 0,
      goodsList: [],
      priceType:0,
      orderSn: undefined,
      actualPrice: 0,
      freightPrice: 0,
      retryCount: 6, // 查询订单结果次数
      retryInterval: 300, // 查询间隔
      type: 0,
    }
  },
  computed: {
    ...mapGetters(['selectedAddress', 'id'])
  },
  async mounted(){
    const opt = this.$route.query
    console.log('传参了吗？==', opt)
    if (Object.keys(opt).length === 0) {
      await this.getGoodsList()
    } else {
      // 传参时的操作
      const id = opt.id
      if (opt.type) {
        const type = opt.type
        this.type = type
        console.log(type)
        console.log(this.goodsList)
        this.goodsList = JSON.parse(sessionStorage.getItem('takeGoods'))
        // this.$set(this, goodsList, JSON.parse(sessionStorage.getItem('takeGoods')))
        console.log(this.goodsList)
      } else {
        await this.getGoods(id)
      }
    }
    this.getInfos()
    this.message = ''
  },
  methods: {
    getInfos() {
      getInfo(this.$store.state.user.token)
        .then(res => {
          const data = res.map
          if (!data) {
            return this.$toast.fail('获取用户信息失败')
          }
          this.userInfo = data.info
          this.$set(this, 'userInfo', data.info)
          // commit('SET_USER_INFO', data.info)
          // resolve(data)
        })
    },
    getGoods(id) {
      this.goodsList = []
    },
    getGoodsList() {
      this.goodsList = []
      getCheckedGoods().then((res) => {
        const { data, orderTotalAmount, goodsAmount, freightPrice, pointAmount } = res.map
        this.goodsList = data
        this.priceType =data[0].priceType
        this.goodsAmount = goodsAmount
        this.pointAmount = pointAmount
        this.orderTotalAmount = orderTotalAmount
        this.freightPrice = freightPrice
      })
    },
    async onSubmit() {
      const addressId = this.selectedAddress.id
      const message = this.message
      const userId = this.id
      if((this.priceType == 1 || this.priceType == 3) && !this.type){
        return this.$toast.fail('支付系统升级中')
      }
      if (!addressId) {
        return this.$toast.fail('请选择地址')
      }
      if (this.goodsList[0].priceType === 2 ) {
        const res = await goodsPointDeduction({ pointNumber: this.orderTotalAmount })
      }
      if ( this.goodsList[0].priceType === 3 && this.userInfo.userPoint < this.pointAmount) {
        return this.$toast.fail('积分不足')
      }

      if (this.type == 0) {
        const cartIdArr = this.goodsList.map((item) => {
          return item.id
        })
        /**
         * 普通商品orderType : 1
         */
        sessionStorage.setItem('orderType', 1)
        sessionStorage.setItem('payRedirct', '/warehouseList/')

        this.$toast.loading({
          duration: 2000, // 持续展示 toast
          forbidClick: true,
          message: '下单中，请稍后'
        })
        this.retryCount = 6
        const data ={ cartIdArr, addressId, userId, message }
        if(this.goodsList[0].priceType === 2){
          data.payType = 4 
        }else if(this.goodsList[0].priceType === 3){
          data.payType = 6
          data.pointAmount = this.pointAmount
        }
        if(this.type == 2){
          data.payType = 5 
        }
        submit(data).then( async (res) => {
          const { orderSn, actualPrice } = res.map
          this.orderSn = orderSn
          this.actualPrice = actualPrice
          if (this.goodsList[0].priceType === 2) {
            console.log(orderSn)
            const ress = await updateOrderState(orderSn)
            this.$router.push('/user/order/list/2')
          } else {
            setTimeout(() => {
              this.searchResult()
            }, this.retryInterval)
          }
        })
      } else {
        const data = this.goodsList[0]
        // data.forEach(item=>{
        //   item.addressId = addressId
        // })
        data.addressId = addressId
        const res = await getGoodsPro(data)
        if (res.code === 200) {
          sessionStorage.removeItem('takeGoods')
          this.$router.push('/user/order/list/2')
        }
        console.log(res)
      }
    },
    /**
     * 查询下单是否成功
     */
    async searchResult() {
      try {
        await searchResult(this.orderSn)
        this.$toast.clear()
        this.$router.push({
          name: 'OrderPay',
          params: { orderSn: this.orderSn, actualPrice: this.actualPrice,priceType: this.goodsList[0].priceType }
        })
      } catch (error) {
        setTimeout(async() => {
          this.retryCount--
          if (this.retryCount > 0) {
            await this.searchResult(this.orderSn)
          } else {
            console.log('下单失败', error)
            this.$toast.fail(error.message)
          }
        }, this.retryInterval)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.list-item {
  box-sizing: border-box;
  width: 100%;
  background: #fff;
  padding: 24px;
  margin-top: 24px;
  .title {
    display: flex;
    flex-direction: row;
    align-items: center;
    .title__name {
      margin-left: 18px;
      font-size: $small;
      color: $black;
    }
  }
  .item {
    position: relative;
    margin-top: 34px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .item__main {
      box-sizing: border-box;
      flex-grow: 1;
      height: 160px;
      display: flex;
      flex-direction: column;
      padding: 0 24px;
      .item__main__desc {
        line-height: 30px;
        font-size: $mini;
        color: $black;
        text-align: justify;
      }
      .item__main__attr {
        margin-top: 12px;
        span {
          display: inline-block;
          background: #f7f7f7;
          border-radius: 6px;
          padding: 6px;
          font-size: $mini;
          color: $gray;
          margin-right: 6px;
        }
      }
      .item__main__id {
        margin-top: 12px;
        font-size: $mini;
        color: $gray;
      }
    }
    .item__price {
      width: 100px;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      .item__price__price {
        font-size: $mini;
        color: $black;
      }
      .item__price__count {
        font-size: $mini;
        color: $gray;
        margin-top: 12px;
      }
    }
  }
}
</style>
